"""
Copyright (c) 2023 - present SKbioinfo
"""
from flask_restful import Resource
from flask import request,jsonify
from flask_jwt_extended import create_access_token,create_refresh_token
from apps.API.electricSigature.AuditRecord import Part11AuditRecord as Arc
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from apps.API.common.common_time import *
from apps.API.auth.models import Role,Users
from apps.API.auth.util import verify_pass
from apps import db

"""URL:/api/auth/Login"""
class interfaceLogin(Resource):
    def get(self):
        try:
            Role.init_role()
            Users.init_user()
            return 202
        except Exception as e:
            lg.error(e)
            return 404
    
    def post(self):
        try:
            username=request.json["username"]
            password=request.json["password"]
            user = Users.query.filter_by(username=username).first()
            if user and verify_pass(password, user.password):
                access_token = create_access_token(identity=username)
                refresh_token = create_refresh_token(identity=username)
                ### SQL: query user info ###
                user_info=db.session.query(
                    Users.username,
                    Users.email,
                    Users.role_id,
                    Role.group,
                    Role.detail,
                    Role.permissions
                ).outerjoin(Role, Users.role_id == Role.name).filter(Users.username == username).first() 
                ### 审计日志记录 ###
                Arc.add_aduit_record(
                    record_type="Login_Success",
                    content=f"{username} Login Success",
                    username=username
                )
                ### 数据输出 ###
                return {
                    "access_token": access_token,
                    "refresh_token":refresh_token,
                    "username": user_info["username"],
                    "group": user_info["group"],
                    "role_id": user_info["role_id"],
                    "detail": user_info["detail"],
                    "permissions": user_info["permissions"]
                },202
            else:
                return 400
        except Exception as e:
            lg.error(e)
            return 404
        
